package com.houhanzhi.component;

import com.houhanzhi.config.SmsConfig;
import com.houhanzhi.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
@Slf4j
public class SmsComponent {

    private static final String urlTemplate = "https://gyytz.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&smsSignId=%s&param=%s";

    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送短信
     * @param to
     * @param value
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to, String value) {

        long start = CommonUtil.getCurrentTimestamp();
        String url = String.format(urlTemplate, to, smsConfig.getTemplateId(), smsConfig.getSignId(), value);

        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        long end = CommonUtil.getCurrentTimestamp();

        log.info("耗时:{},url={},body={}", end-start, url, response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}", response.getBody());
        }
    }
}
